package com.ziytek.web.citizen.service.impl;

import com.ziytek.web.citizen.constant.SettingConstant;
import com.ziytek.web.citizen.enums.ResponseEnum;
import com.ziytek.web.citizen.mapper.LoginMapper;
import com.ziytek.web.citizen.service.itf.AdminService;
import com.ziytek.web.citizen.util.StringUtil;
import com.ziytek.web.citizen.util.TokenUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @className AdminServiceImpl
 * @description: 管理员权限接口实现类
 * @jdkVersion: 1.8
 * @author: fhx
 * @date: 2024/7/2 9:53
 */
@Lazy
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AdminServiceImpl implements AdminService {

    private final LoginMapper loginMapper;
    private static final String EMPTY_TOKEN = "null";

    @Override
    public boolean hasAdminPermission(String token) {
        if (StringUtils.isEmpty(token) || EMPTY_TOKEN.equalsIgnoreCase(token)) {
            return false;
        }

        var accessToken = TokenUtils.getAccessToken(token);
        if (accessToken == null) {
            return false;
        }

        var login = loginMapper.findByUserNameAndAvailableOrderByCreateTimeDesc(accessToken.getUserId(), SettingConstant.IS_AVAILABLE);
        if (login == null) {
            return false;
        }

        return StringUtil.isNotEmpty(login.getRole()) && ResponseEnum.ROLE_ADMIN.getCode().equalsIgnoreCase(login.getRole());
    }
}
